#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <functional>
#include <sys/syscall.h> 
#include "Log.hpp"


#define get_lwp_id() syscall(SYS_gettid)

using func_t = std::function<void(const std::string &name)>;


class Thread
{
public:
    Thread(func_t func, std::string name = "None-name")
            : _name(name),
              _func(func),
              _running(false)
    {
        LOG(LogLevel::INFO) << _name << "create thread success";
    }

    static void* start_routine(void* args)
    {
        Thread* self = static_cast<Thread*>(args);
        self->_running = true;
        self->_lwpid = get_lwp_id();
        self->_func(self->_name);//执行对应函数
        pthread_exit((void*)0);//退出

    }

    void Start()
    {
        int n = pthread_create(&_tid, nullptr, start_routine, this);
        if(n == 0)
        {
            LOG(LogLevel::INFO) << _name << "run thread success";
        }
    }

    void Join()
    {
        if(_running = false)
            return;

        int m = pthread_join(_tid, nullptr);
         if (m == 0)
        {
            LOG(LogLevel::INFO) << _name << "destory thread success";
        }
 
    }

    void Stop()
    {
        pthread_cancel(_tid);
    }

    ~Thread()
    {
        //  LOG(LogLevel::INFO) << _name << "pthread_join success";
    }
private:
    pthread_t _tid;
    func_t _func;
    std::string _name;
    pid_t _lwpid;
    bool _running;

};